package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.StudentClass;
import cn.edu.sdjzu.xg.kcsj.exception.JwkqException;
import cn.edu.sdjzu.xg.kcsj.service.StudentClassService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import util.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/deleteStudentClass.ctl")
public class DeleteStudentClassController extends HttpServlet {
    @Override
    protected void doDelete (HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {

        JSONObject respMessage = new JSONObject ();
        resp.setContentType ("application/json;charset=UTF-8");
        String id_str = req.getParameter ("id");
        if (id_str == null){
            respMessage.put ("message","no have request");
        }else {
            int id = Integer.parseInt (id_str);
            try {
                if (StudentClassService.getInstance().delete(id)){
                    respMessage.put ("message","delete yes");
                }else {
                    respMessage.put ("message","delete no");
                }
            } catch (SQLException | JwkqException throwables) {
                throwables.printStackTrace ();
                respMessage.put ("message","sjk have exception");
            }
        }
        resp.getWriter ().println (respMessage);
    }
    @Override
    protected void doPost (HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        JSONObject respMessage = new JSONObject();
        String request_json= JSONUtil.getJSON(req);
        JSONObject req_jsonObj = JSON.parseObject(request_json);
        JSONArray List_jsonArray =
                req_jsonObj.getJSONArray("ListToDelete");
        List<StudentClass> listToDelete = null;
        listToDelete= List_jsonArray.toJavaList(StudentClass.class);
        try {
            if (StudentClassService.getInstance().deletes(listToDelete)){
                respMessage.put("message", "deletes yes");
            }else {
                respMessage.put("message", "deletes no");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace ();
            respMessage.put("message", "sjk have exception");
        }
        resp.getWriter ().println (respMessage);
    }
}
